package com.hncc.kumao.interceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hncc.kumao.util.ConstValue;
import com.hncc.kumao.util.JSONUtils;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

public class RequestDataInterceptor extends MethodFilterInterceptor {

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        //System.out.println("验证数据");
        String data = JSONUtils.getJsonByRequest(ServletActionContext.getRequest());
        if(data == null || data.trim().length() <= 0) {
            jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "请求参数不能为空");
            return null;
        }
        //没有问题，将数据存入request
        ServletActionContext.getRequest().setAttribute(ConstValue.REQUEST_DATA, data);
        return invocation.invoke();
    }
    
    //返回json格式数据
    public void jsonReturn(boolean success, int code, Object value) {
       Map map = new HashMap();
       map.put(ConstValue.SUCCESS, success);
       map.put(ConstValue.CODE, code);
       map.put(ConstValue.DATA, value);
       HttpServletResponse response = ServletActionContext.getResponse();
       response.setContentType("text/html;charset=UTF-8");
       response.setCharacterEncoding("UTF-8");
       try {
           String jsonString = JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect);
           //System.out.println(jsonString);
           response.getWriter().write(jsonString);
       } catch (IOException e) {
           e.printStackTrace();
       }
    }
}
